package com.example.nio.two;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Description
 * @Author 26233
 * @Create 2021-10-28 16:21:46
 */

public class ReadSelectorThread2 implements Runnable {
    private Selector readSelector;
    private TaskDispacther taskDispacther;

    public ReadSelectorThread2(Selector readSelector) {
        this.readSelector = readSelector;
    }

    public ReadSelectorThread2(Selector readSelector, TaskDispacther taskDispacther) {
        this.readSelector = readSelector;
        this.taskDispacther = taskDispacther;
    }

    @Override
    public void run() {
        System.out.println("read thread start...");
        while (true){
            try {
                readSelector.select();
                Set<SelectionKey> selectionKeys = readSelector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    try {
                        if (selectionKey.isValid()){
                            if (selectionKey.isReadable()){
                                System.out.println("add");

                                selectionKey.cancel();
                                taskDispacther.addSocketChannel((SocketChannel) selectionKey.channel());
                            }else {
                                System.out.println("select key is not readable");
                            }
                        }
                    }catch (Exception e){
                        // e.printStackTrace();
                        selectionKey.channel().close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
